package code.wrtp.packets;

import code.exceptions.BadPduFormatException;
import code.wrtp.FrameControlType;

public class Election implements Packet {

	private byte FC; /* Frame control field */
	private short SA; /* Source Address field */
	private short RA; /* Ring Address */
	private short DA; /* Destination Address */
	private double maxPower; /* Maximum power among nodes */
	private short coordinator; /* ID of coordinator candidate */
	private long numCh; /* Number of challenging nodes in election */

	public Election(byte FC, short SA, short RA, short DA, double maxPower,
			short coordinator, long numCh) {
		this.FC = FC;
		this.SA = SA;
		this.RA = RA;
		this.DA = DA;
		this.maxPower = maxPower;
		this.coordinator = coordinator;
		this.numCh = numCh;
	}

	public byte getFC() {
		return FC;
	}

	public short getSA() {
		return SA;
	}

	public short getRA() {
		return RA;
	}

	public short getDA() {
		return DA;
	}

	public double getMaxPower() {
		return maxPower;
	}

	public short getCoordinator() {
		return coordinator;
	}

	public long getNumCh() {
		return numCh;
	}

	@Override
	public byte[] toBytes() {
		return toString().getBytes();
	}

	@Override
	public String toString() {
		String token = FC + ";" + RA + ";" + DA + ";" + SA + ";" + maxPower
				+ ";" + coordinator + ";" + numCh;
		return token;
	}

	@Override
	public void ParseBytes(byte[] pduRaw) throws BadPduFormatException {

		String[] splittedPacket = new String(pduRaw).split(";", 7);

		if (splittedPacket.length != 7) {
			throw new BadPduFormatException("Wrong packet format");
		}

		FC = Byte.parseByte(splittedPacket[0]);
		if ((FC != FrameControlType.ELECTION_TOKEN)
				&& (FC != FrameControlType.VARAL_ELECTION_TOKEN))
			throw new BadPduFormatException("Wrong packet format");
		RA = Short.parseShort(splittedPacket[1]);
		DA = Short.parseShort(splittedPacket[2]);
		SA = Short.parseShort(splittedPacket[3]);
		maxPower = Double.parseDouble(splittedPacket[4]);
		coordinator = Short.parseShort(splittedPacket[5]);
		numCh = Long.parseLong(splittedPacket[6]);
	}
}